//
//  HMTabBar.swift
//  TJHWeiBo
//
//  Created by tianjunhui on 16/8/9.
//  Copyright © 2016年 itcast.cn. All rights reserved.
//

import UIKit

//声明协议 需要继承NSObjectProtocol
protocol HMTabBarDelegate:NSObjectProtocol{
    
    //声明方法
    func tabBarButtonClick()
}


class HMTabBar: UITabBar {

    //声明一个代理
    weak var hmDelegate:HMTabBarDelegate?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setUI()
    }
    //纯代码必须写
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //添加视图
    private func setUI(){
        
        addSubview(composebutton)
        
    }
    //给tabBar设置frame
    override func layoutSubviews() {
        super.layoutSubviews()
        
        var index : CGFloat = 0
        
        //遍历子控件
        for value in self.subviews {
            if value.isKindOfClass(NSClassFromString("UITabBarButton")!) {
                //设置frame
                value.frame.size.width = self.frame.width * 0.2
                value.frame.origin.x = index * self.frame.width * 0.2
                index++
                
                if index == 2 {
                    index++
                }
            }
            composebutton.center.x = self.frame.width * 0.5
            composebutton.center.y = self.frame.height * 0.5
    }
}
    
    //懒加载控件
    private lazy var composebutton: UIButton = {
        
       
        
        
        //创建一个button
        let buttom = UIButton()
        
         //响应点击事件
        
        buttom.addTarget(self, action: #selector(HMTabBar.buttonClick), forControlEvents: UIControlEvents.TouchUpInside)
        
        //设置背景图片
        buttom.setBackgroundImage(UIImage (named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        buttom.setBackgroundImage(UIImage (named: "tabbar_compose_button"), forState: UIControlState.Normal)
        
        buttom.setImage(UIImage (named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        buttom.setImage(UIImage (named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        
        buttom.sizeToFit()
        return buttom
        
    }()
    
    //响应点击事件
    func buttonClick(){
      
        hmDelegate?.tabBarButtonClick()
    }

}
